package com.mengze.linlee_iot_adnroid.adapter

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.mengze.linlee_iot_adnroid.R

class ProductCategoryAdapter (
    private val categories: List<String>,
    private val onItemClick: (String) -> Unit
) : RecyclerView.Adapter<ProductCategoryAdapter.ViewHolder>() {

    private var selectedPosition = 0

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val tvCategory: TextView = view.findViewById(R.id.tvCategory)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.product_category_item, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) {
        holder.tvCategory.text = categories[position]
        holder.tvCategory.setTextColor(
            if (position == selectedPosition) Color.parseColor("#FF6fd04d") else Color.parseColor("#ff333333")
        )

        holder.itemView.setBackgroundColor(
            if (position == selectedPosition) Color.LTGRAY else Color.TRANSPARENT
        )
        holder.itemView.setOnClickListener {
            selectedPosition = position
            notifyDataSetChanged()
            onItemClick(categories[position])
        }
    }

    override fun getItemCount() = categories.size

    fun selectFirstItem() {
        if (categories.isNotEmpty()) {
            onItemClick(categories[0])
        }
    }
}


